﻿using System;
using System.Linq;
using System.Threading;

namespace WinHID.USB
{
    internal class HIDHelper
    {
        static HIDDevice hd = null;
        public static bool isOpen
        {
            get
            {
                if (hd != null && hd.deviceConnected)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }

        public static bool Open()
        {
            bool b = false;
            if (isOpen)
            {
                b = true;
            }
            else
            {
                try
                {
                    hd = new HIDDevice(PUB.VID, PUB.PID, false);
                    if (hd.deviceConnected)
                    {
                        b = true;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("打开USB异常：" + ex.Message);
                }
            }
            return b;
        }

        public static void Send(byte[] bytes)
        {
            hd.send(bytes);
        }
        public static byte[] Read()
        {
            return hd.read();
        }

        public static SCD Collect(SCD send, int sleep = 50)
        {
            SCD read = null;
            try
            {
                Send(send.BYTES);
            }
            catch (Exception ex)
            {
                throw new Exception("发送出错：" + ex.Message);
            }
            if (sleep >= 1) Thread.Sleep(sleep);
            try
            {
                byte[] bR = Read();
                if (bR != null && bR.Length >= 1)
                {
                    int iSkip = 0;
                    for (int i = 0; i < bR.Length; i++)
                    {
                        if (bR[i] == 0xFC)
                        {
                            iSkip = i;
                            break;
                        }
                    }
                    if (iSkip >= 1)
                    {
                        bR = bR.Skip(iSkip).ToArray();
                    }
                    if (bR.Length >= 64)
                    {
                        read = new SCD(bR);
                    }
                    else
                    {
                        throw new Exception($"接收长度不够,Skip:{iSkip},Length:{bR.Length}");
                    }
                }
                else
                {
                    throw new Exception("接收为空");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("接收出错：" + ex.Message);
            }
            return read;
        }

        public static bool Close()
        {
            hd.close();
            hd = null;
            return true;
        }
    }
}
